package cn.edu.cdp.dumpling.service.impl;

import cn.edu.cdp.dumpling.entity.Dish;
import cn.edu.cdp.dumpling.entity.OrderDetail;
import cn.edu.cdp.dumpling.entity.OrderList;
import cn.edu.cdp.dumpling.entity.ShoppingCart;
import cn.edu.cdp.dumpling.mapper.OrderListMapper;
import cn.edu.cdp.dumpling.service.DishService;
import cn.edu.cdp.dumpling.service.OrderDetailService;
import cn.edu.cdp.dumpling.service.OrderListService;
import cn.edu.cdp.dumpling.service.ShoppingCartService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class OrderListServiceImpl extends ServiceImpl<OrderListMapper, OrderList> implements OrderListService {

    private final OrderDetailService orderDetailService;
    private final DishService dishService;

    public OrderListServiceImpl(OrderDetailService orderDetailService, DishService dishService) {
        this.orderDetailService = orderDetailService;
        this.dishService = dishService;
    }
    @Override
    public List<OrderList> getOrderListAndDetail(Integer consumerId) {
        LambdaQueryWrapper<OrderList> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(OrderList::getConsumerId, consumerId);
        List<OrderList> orderListList = this.list(wrapper1);

        // 把订单详情添加到 OrderList 对象中
        if (orderListList == null || orderListList.isEmpty()) {
            return null;
        } else {
            return orderListList.stream().peek((item) -> {
                // 通过订单编号，查询订单详情
                LambdaQueryWrapper<OrderDetail> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(OrderDetail::getOrderListId, item.getId());
                List<OrderDetail> orderDetailList = orderDetailService.list(wrapper2);

                // 通过订单详情的 dish_id 查询，并把 Dish 对象添加到 DishDetail 中
                if (orderDetailList != null) {
                    for (OrderDetail orderDetail : orderDetailList) {
                        LambdaQueryWrapper<Dish> wrapper3 = new LambdaQueryWrapper<>();
                        wrapper3.eq(Dish::getId, orderDetail.getDishId());
                        Dish dish = dishService.getOne(wrapper3);
                        orderDetail.setDish(dish);
                    }
                }


                item.setOrderDetailList(orderDetailList);

            }).toList();
        }
    }
}
